package com.shengsiyuan.netty.firstexample;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * 自定义处理器
 *
 * Inbound是网络编程中常用的属术语
 * 进来的是Inbound
 * 出去的是Outbound
 *
 * 连接进来时  handlerAdded-》channelRegistered-》channelActive-》channelRead0-》channelInactive-》channelUnregistered
 */
public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 功能描述：读取客户端发过来的请求，并且向客户端返回响应的方法。
     *
     * netty并没有实现servlet规范，所以这里并没有request和response之类的。
     *
     * Please keep in mind that this method will be renamed to messageReceived(ChannelHandlerContext, I) in 5.0.
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //System.out.println("------执行channelRead0");
        System.out.println(msg.getClass());

        // 获取远程地址
        System.out.println(ctx.channel().remoteAddress());

        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;

            //System.out.println("******执行channelRead0");
            System.out.println("请求方法名：" + httpRequest.method().name());

            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求favicon.ico");
                return;
            }

            // 向客户端返回的相应内容
            ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 返回客户端
            ctx.writeAndFlush(response);
            //ctx.write(response); // 调用此方法并不会立刻返回客户端，会放入缓冲区中

            ctx.channel().close();
        }
    }

    /**
     * 当 channel 变成活动状态的时候会执行此方法。
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active");
        super.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel registered");
        super.channelRegistered(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handler added");
        super.handlerAdded(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel inactive");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel unregistered");
        super.channelUnregistered(ctx);
    }
}
